var act = 'add';

$('#btnAdd').click(function () {
    var msg = '';
    if (act === 'add') msg = '添加数据';
    if (act === 'modify') msg = '修改数据';

    $.ajax({
        url: '/student/' + act,
        method: 'post',
        data: $('#frmInput').serialize()
    }).then(res => {
        if (res.msg === 'OK') {
            alert(msg + '成功！');
        } else {
            alert(msg + '失败！')
        }
        window.location.href = '/student';
    });

});

// 删除指定学号的学生信息
function del(sNo) {
    $.ajax({
        url: '/student/del',
        method: 'post',
        data: 'sNo=' + sNo
    }).then(res => {
        if (res.msg === 'OK') {
            alert('删除数据成功！');
        } else {
            alert('删除数据失败！')
        }
        window.location.href = '/student';
    });
}

// 修改指定学号的学生信息
function modify(stu) {

    act = 'modify';

    $('div.mask').show();

    $('input[name=sNo]').val(stu.sNo);
    $('input[name=sName]').val(stu.sName);
    $('input[name=sBirthday]').val(stu.sBirthday.substr(0, 10));
    $('select[name=class]').val(stu.class);
    var radios = $('input[name=sSex]');
    for (var radio of radios) {
        radio.checked = (radio.value === stu.sSex);
    }

    $('p.title > span:first-child').text('修改学生信息');
    $('#btnAdd').val('修改信息');
}

$('span.close').click(function () {
    $('div.mask').hide();
});

$('span#addStudent').click(function () {

    act = 'add';
    
    $('div.mask').show();
    $('input[name=sNo]').val('');
    $('input[name=sName]').val('');
    $('input[name=sBirthday]').val('');
    $('select[name=class]').val('');
    var radios = $('input[name=sSex]');
    for (var radio of radios) {
        radio.checked = false;
    }

    $('p.title > span:first-child').text('学生信息录入');
    $('#btnAdd').val('添加学生');
});

$('span#filterClass > select').change(function(){
    $.ajax({
        url: '/student/filter',
        method: 'post',
        data: 'class=' + $(this).val()
    }).then(res => {
        console.log(res);
        $('table > tbody').html(res)
    });
});